<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Item extends CI_Controller
{
    private $TB;
    private $token;
    private $tb_nick;
    private $data;

    function __construct()
    {
        parent::__construct();
        $this->load->library('Taobao/TopSdk');
        $this->TB = new TopClient;
        $this->TB->appkey = $this->config->item('tb_akey');
        $this->TB->secretKey = $this->config->item('tb_skey');
        $this->token = $this->session->userdata('token');
        $this->tb_nick = $this->session->userdata('tb_nick');
        $this->data['tb_is_login'] = $this->session->userdata('tb_is_login');
        $this->data['tb_nick'] = $this->session->userdata('tb_nick');
        $this->load->model('item_model');
    }


    public function index()
    {
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
            $param = $this->input->get_post('Form');
            $param['ids'] = $this->transform_string($param['ids']);
            $this->copy_items_ini($param);
        }
        $this->data['form_url'] = site_url('item/index');
        $this->load->view('item/index', $this->data);
    }

    // 复制宝贝记录

    public function copy_record_list()
    {

        $where = "";
        $condition['word'] = addslashes($this->input->get_post('word'));
        $condition['status'] = addslashes($this->input->get_post('status'));

        if ($condition['word']) {
            $where .= "desc LIKE '%" . $condition['word'] . "%'";
        }

        if ($condition['status']) {
            if ($where !== '')
                $where .= " AND ";
            $where .= "status = 0";
        }

        $page_config['perpage'] = 20;   //每页条数
        $page_config['part'] = 2;//当前页前后链接数量
        $page_config['url'] = 'member/admin/member_list';//url
        $page_config['param'] = '?word=' . $condition['word'];//参数
        $page_config['seg'] = 4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex'] = $this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']) : 1;//当前页
        $page_config['total'] = $this->item_model->get_record_count($where);
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);
        $list_array = $this->item_model->get_record_list($where, $page_config['perpage'], $page_config['nowindex']);
        foreach ($list_array as $k => $v) {
            if (!$v['created']) {
                $list_array[$k]['created'] = '/';
            }
            else {
                $list_array[$k]['created'] = date('Y-m-d H:i:s', $v['created']);
            }
            if (!$v['desc'])
                $list_array[$k]['desc'] = '/';
            if (!$v['detail_url'])
                $list_array[$k]['detail_url'] = '#';
            if (!$v['error'])
                $list_array[$k]['error'] = '/';
            $list_array[$k]['crts'] = date('Y-m-d H:i:s', $v['crts']);
        }
        $this->data['list'] = $list_array;
        $this->data['form_url'] = site_url('item/copy_record_list');
        $this->data['condition'] = $condition;
        $this->load->view('item/record_list', $this->data);
    }

    /*
     * 过滤商品ID (支持链接复制或ID)
     * @param string
     * return Array
     * */

    public function transform_string($strings)
    {
        $ids = array();
        $strings = str_replace(array('<br />',), ',', nl2br($strings));
        $data = array_filter(explode(',', $strings));
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                if (is_numeric($v)) {
                    $ids[$k] = $v;
                }
                else {
                    // 验证URL合法
                    if (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $v)) {
                        $urlarr = parse_url($v);
                        @parse_str($urlarr['query'], $parr);
                        if (isset($parr['id']))
                            $ids[$k] = $parr['id'];
                    }
                }
            }
            $return_ids = array_unique(array_filter($ids));
            if (!empty($return_ids)) {
                return $return_ids;
            }
            $this->error('无法识别的宝贝', '#');
        }
    }


    public function shop()
    {
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'GET') {
            $nickname = $this->input->get_post('words');
            $num_iid = $this->input->get_post('num_iid');
            $this->data['shop'] = $this->info($nickname);
            $this->data['words'] = $nickname;
            $this->data['num_iid'] = $num_iid;
            $this->data['list'] = $this->goods_detail($num_iid);
        }
        $this->data['form_url'] = site_url('item/shop');
        $this->load->view('item/shop', $this->data);
    }


    /*
     * 商品详情
     * @param $id 商品 id
     * return Array
     *
     * */

    public function goods_detail($num_iid)
    {
        if (!empty($num_iid)) {
            $req = new ItemGetRequest;
            $req->setFields("detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
            $req->setNumIid($num_iid);
            $resp = _object_array($this->TB->execute($req, $this->token));
            if (isset($resp['item']) && !empty($resp['item'])) {
                $resp['item']['sku'] = $this->get_goods_sku($num_iid);
                return $resp['item'];
            }
            return false;
        }
    }

    /*
    * 批量复制宝贝
    * @param Array $ids
    * return Array 成功数量 失败数量
    *
    * */

    public function copy_items_ini($params)
    {
        $success = 0;
        $failure = 0;
        $invalid = 0;
        if (!empty($params['ids']) && is_array($params['ids'])) {

            foreach ($params['ids'] as $k => $v) {
                $detail = $this->goods_detail($v);
                if (!empty($detail) && isset($detail)) {
                    $detail = $this->copy_replace_ini($detail, $params);
                    $return = $this->copy_item($detail);
                    if ($return['status']) {
                        $data = array('onum_iid' => $v, 'num_iid' => $return['num_iid'], 'created' => strtotime($return['created']), 'crts' => time(), 'status' => '1');

                        if ($this->item_model->copy_log_add($data)) {
                            $success++;
                        }
                    }
                    else {
                        $data = array('onum_iid' => $v, 'desc' => $return['desc'], 'detail_url' => $return['detail_url'], 'error' => $return['error'], 'crts' => time(), 'status' => '0');

                        if ($this->item_model->copy_log_add($data)) {
                            $failure++;
                        }
                    }
                }
                else {
                    $invalid++;
                }
            }

        }

        $this->success('成功复制宝贝' . $success . '个,失败' . $failure . '个,无效宝贝链接' . $invalid . '个', site_url('item/copy_record_list'));
    }

    /*
     * 复制条件
     * @param Array $detail 商品详细信息
     * @param Array $params 过滤条件
     * return Array 成功数量 失败数量
     *
     * */

    public function copy_replace_ini($detail, $params)
    {
        if ($params['price']) {
            if ($params['multiply']) {
                $detail['price'] = intval($detail['price'] * $params['multiply']);
            }
            elseif ($params['plus']) {
                $detail['price'] = intval($detail['price'] + $params['plus']);
            }
            elseif ($params['minus']) {
                $detail['price'] = intval($detail['price'] - $params['minus']);
            }
        }

        if ($params['prefix'])
            $detail['title'] = $params['prefix'] . '' . $detail['title'];
        if ($params['suffix'])
            $detail['title'] = $detail['title'] . '' . $params['suffix'];
        if ($params['target']) {
            if ($params['replace']) {
                mb_ereg_replace($params['target'], ' ', $detail['title']);
            }
            else {
                mb_ereg_replace($params['target'], $params['replace'], $detail['title']);
            }
        }

        return $detail;
    }

    /*
     * 过滤复制过的ids
     * @param Array $ids 商品ids
     * return Array 成功数量 失败数量
     *
     * */

    public function filter_ids($ids)
    {
        $oids = $this->item_model->get_record_oids();

    }

    public function copy_item($data)
    {
        if (!is_array($data) || empty($data)) {
            return false;
        }

        $num = @$data['num'] ? $data['num'] : '1';
        $price = @$data['price'] ? $data['price'] : '1';
        $type = @$data['type'] ? $data['type'] : 'fixed';
        $stuff_status = @$data['stuff_status'] ? $data['stuff_status'] : 'new';
        $title = @$data['title'] ? $data['title'] : '请添加标题';
        $desc = @$data['desc'] ? $data['desc'] : '<p>请添加描述</p>';
        $state = @$data['location']['state'] ? $data['location']['state'] : '江苏';
        $city = @$data['location']['city'] ? $data['location']['city'] : '南京';
        $approve_status = @$data['approve_status'] ? $data['approve_status'] : 'onsale';
        $cid = @$data['cid'] ? $data['cid'] : '000001';
        $props = !empty($data['props']) ? $data['props'] : '';
        $freight_payer = @$data['freight_payer'] ? $data['freight_payer'] : 'seller';
        $valid_thru = @$data['valid_thru'] ? $data['valid_thru'] : '14';
        $has_invoice = @$data['has_invoice'] ? $data['has_invoice'] : true;
        $has_warranty = @$data['has_warranty'] ? $data['has_warranty'] : false;
        $has_showcase = @$data['has_showcase'] ? $data['has_showcase'] : false;
        $seller_cids = @$data['seller_cids'] ? $data['seller_cids'] : '';
        $has_discount = @$data['has_discount'] ? $data['has_discount'] : false;
        $post_fee = @$data['post_fee'] ? $data['post_fee'] : '6';
        $express_fee = @$data['express_fee'] ? $data['express_fee'] : '6';
        $ems_fee = @$data['ems_fee'] ? $data['ems_fee'] : '20';
        $list_time = date('Y-m-d H:i:s', time());
        $increment = @$data['increment'] ? $data['increment'] : '0';
        $image = '';
        if (is_array($data['item_imgs']) && !empty($data['item_imgs'])) {
            $resource = file_get_contents($data['item_imgs']['item_img']['url']);
            $file_name = FCPATH . '/static/item/' . time() . '.jpg';
            if (write_file($file_name, $resource))
                $image = $file_name;
        }

        $postage_id = @$data['postage_id'] ? $data['postage_id'] : '0';
        $auction_point = @$data['auction_point'] ? $data['auction_point'] : '1';
        $property_alias = @$data['property_alias'] ? $data['property_alias'] : '';
        $input_pids = @$data['input_pids'] ? $data['input_pids'] : '';

        if (is_array($data['sku']) && !empty($data['sku'])) {
            foreach ($data['sku'] as $k => $v) {
                $properties[$k] = $v['properties'];
                $quantities[$k] = $v['quantity'];
                $prices[$k] = $v['price'];
                $outerids[$k] = $v['outer_id'];
            }

            if (!empty($properties))
                $sku_properties = implode(',', $properties);
            if (!empty($quantities))
                $sku_quantities = implode(',', $quantities);
            if (!empty($prices))
                $sku_prices = implode(',', $prices);
            if (!empty($outerids))
                $sku_outerids = implode(',', $outerids);
        }


        $lang = @$data['lang'] ? $data['lang'] : '';
        $outer_id = @$data['outer_id'] ? $data['outer_id'] : '111';
        $product_id = @$data['product_id'] ? $data['product_id'] : '111';
        $pic_url = '';
        if (empty($image) && isset($data['pic_url']) && !empty($data['pic_url'])) {
            $resource = file_get_contents($data['item_imgs']['item_img']['url']);
            $file_name = FCPATH . '/static/item/' . time() . '.jpg';
            if (write_file($file_name, $resource))
                $pic_url = $file_name;
        }

        $auto_fill = @$data['auto_fill'] ? $data['auto_fill'] : 'no_mark';
        $input_str = @$data['input_str'] ? $data['input_str'] : '';
        $is_ex = @$data['is_ex'] ? $data['is_ex'] : false;
        $is_taobao = @$data['is_taobao'] ? $data['is_taobao'] : false;
        $is_3D = @$data['is_3D'] ? $data['is_3D'] : false;
        $sell_promise = @$data['sell_promise'] ? $data['sell_promise'] : false;
        /* $after_sale_id  = $data['after_sale_id']?$data['after_sale_id']:'';
           $is_lightning_consignment  = $data['is_lightning_consignment']?$data['is_lightning_consignment']:false;
           $weight         = $data['weight']?$data['weight']:'';
           $is_xinpin         = $data['is_xinpin']?$data['is_xinpin']:false;*/

        $req = new ItemAddRequest;
        $req->setNum($num);
        $req->setPrice($price);
        $req->setType($type);
        $req->setStuffStatus($stuff_status);
        $req->setTitle($title);
        $req->setDesc($desc);
        $req->setLocationState($state);
        $req->setLocationCity($city);
        $req->setApproveStatus($approve_status);
        $req->setCid($cid);
        $req->setHasInvoice($has_invoice);
        $req->setHasWarranty($has_warranty);
        $req->setProps($props);
        $req->setFreightPayer($freight_payer);
        $req->setValidThru($valid_thru);
        $req->setHasShowcase($has_showcase);
        $req->setSellerCids($seller_cids);
        $req->setHasDiscount($has_discount);
        $req->setPostFee($post_fee);
        $req->setExpressFee($express_fee);
        $req->setEmsFee($ems_fee);
        $req->setListTime($list_time);
        $req->setPostageId($postage_id);
        $req->setAuctionPoint($auction_point);
        $req->setPropertyAlias($property_alias);
        $req->setInputPids($input_pids);
        $req->setInputStr($input_str);
        $req->setLang($lang);
        $req->setAutoFill($auto_fill);
        $req->setIsTaobao($is_taobao);
        $req->setIsEx($is_ex);
        $req->setIs3D($is_3D);
        $req->setSellPromise($sell_promise);
        $req->setPicPath($pic_url);
        $req->setOuterId($outer_id);
        $req->setProductId($product_id);
        $req->setImage('@' . $image);
        if (is_array($data['sku']) && !empty($data['sku'])) {
            if (!empty($sku_properties))
                $req->setSkuProperties($sku_properties);
            if (!empty($sku_quantities))
                $req->setSkuQuantities($sku_quantities);
            if (!empty($sku_prices))
                $req->setSkuPrices($sku_prices);
            if (!empty($sku_outerids))
                $req->setSkuOuterIds($sku_outerids);
        }

        /*
        $req->setChaoshiExtendsInfo(0);
        $req->setPicPath("i7/T1rfxpXcVhXXXH9QcZ_033150.jpg");
        $req->setIncrement("2.50");
        $req->setImage(@fileLocation);
        $req->setDescModules("[{"ModuleId":123,"ModuleName":"模特图","type":"cat_mod","content":"模特要漂亮一点拜托"},{"ModuleId":null,"ModuleName":"店主最漂亮","type":"usr_mod","content":"老娘全网最美"}]");
        $req->setAfterSaleId(47758);
        $req->setCodPostageId(53899);
        $req->setIsLightningConsignment("true");
        $req->setWeight(100);
        $req->setIsXinpin("false");
        $req->setSubStock(1);
        $req->setFoodSecurityPrdLicenseNo("QS410006010388");
        $req->setFoodSecurityDesignCode("Q/DHL.001-2008");
        $req->setFoodSecurityFactory("远东恒天然乳品有限公司");
        $req->setFoodSecurityFactorySite("台北市仁爱路4段85号");
        $req->setFoodSecurityContact("00800-021216");
        $req->setFoodSecurityMix("有机乳糖、有机植物油");
        $req->setFoodSecurityPlanStorage("常温");
        $req->setFoodSecurityPeriod("2年");
        $req->setFoodSecurityFoodAdditive("磷脂 、膨松剂");
        $req->setFoodSecuritySupplier("深圳岸通商贸有限公司");
        $req->setFoodSecurityProductDateStart("2012-06-01");
        $req->setFoodSecurityProductDateEnd("2012-06-10");
        $req->setFoodSecurityStockDateStart("2012-06-20");
        $req->setFoodSecurityStockDateEnd("2012-06-30");
        $req->setSkuSpecIds("123,123,1243");
        $req->setScenicTicketPayWay(1);
        $req->setScenicTicketBookCost("5.99");
        $req->setItemSize("bulk:8");
        $req->setItemWeight("10");
        $req->setChangeProp("162707:28335:28335,28338");
        $req->setSellPoint("2013新款 时尚 前卫");
        $req->setFoodSecurityHealthProductNo("卫食健字(1997)第167号");
        $req->setIsOffline("1");
        $req->setBarcode("6903244981002");
        $req->setSkuBarcode("6903244981002");
        $req->setNewprepay("1");
        $req->setSkuHdLength("20,30,30");
        $req->setSkuHdHeight("15-25,25-50,25-50");
        $req->setSkuHdLampQuantity("3,5,7");
        $req->setQualification("string");
        $req->setO2oBindService("true");
        $req->setLocalityLifeExpirydate("2012-08-06,2012-08-16");
        $req->setLocalityLifeNetworkId("5645746");
        $req->setLocalityLifeMerchant("56879:码商X");
        $req->setLocalityLifeVerification("101");
        $req->setLocalityLifeRefundRatio(50);
        $req->setLocalityLifeOnsaleAutoRefundRatio(80);
        $req->setLocalityLifeRefundmafee("b");
        $req->setLocalityLifeChooseLogis("0");
        $req->setGlobalStockType("1");
        $req->setGlobalStockCountry("美国");
        $req->setPaimaiInfoMode(1);
        $req->setPaimaiInfoDeposit(20);
        $req->setPaimaiInfoInterval(5);
        $req->setPaimaiInfoReserve("11");
        $req->setPaimaiInfoValidHour(2);
        $req->setPaimaiInfoValidMinute(22);
        */
        $resp = _object_array($this->TB->execute($req, $this->token));
        delete_files($file_name);
        if (isset($resp['item']) && !empty($resp['item'])) {
            if (!empty($resp['item']['num_iid'])) {
                return array('status' => '1', 'num_iid' => $resp['item']['num_iid'], 'created' => $resp['item']['created']);
            }
        }

        return array('status' => '0', 'desc' => $data['desc'], 'detail_url' => $data['detail_url'], 'error' => $resp['sub_msg']);
    }

    // 单个复制宝贝

    public function copy_item_action($id)
    {
        if (!empty($id)) {
            $detail = $this->goods_detail($id);

            if (!empty($detail[0]) && isset($detail)) {
                $this->copy_item($detail[0]);
            }
        }
    }


    // 获取商品SKU
    public function get_goods_sku($num_iid)
    {
        $req = new ItemSkusGetRequest;
        $req->setFields("sku_id,num_iid,properties,quantity,price,outer_id,created,modified");
        $req->setNumIids($num_iid);
        $resp = _object_array($this->TB->execute($req));
        if (!empty($resp['skus']))
            return $resp['skus'];
        return false;
    }

    // 卖家自定义分类

    public function seller_category()
    {
        $req = new SellercatsListGetRequest;
        $req->setNick($this->tb_nick);
        $resp = _object_array($this->TB->execute($req));
        print_r($resp);
    }

    // 发布商品基础类


    public function standard_category()
    {
        $req = new ItemcatsGetRequest;
        $req->setFields("cid,parent_cid,name,is_parent");
        $req->setParentCid(0);
        $resp = _object_array($this->TB->execute($req));
        if (!empty($resp['item_cats']['item_cat']) && isset($resp['item_cats']['item_cat'])) {
            $this->data['list'] = $resp['item_cats']['item_cat'];
        }
        $this->load->view('shop/standard_category', $this->data);
    }

    public function item_add_img($num_iid, $data)
    {
        $req = new ItemImgUploadRequest;
        $req->setNumIid($num_iid);
        $req->setPosition($data['position']);
        //附件上传的机制参见PHP CURL文档，在文件路径前加@符号即可
        //$req->setImage(@fileLocation);
        $req->setImage(@$data['url']);
        $resp = _object_array($this->TB->execute($req, $this->token));
        return $resp;

    }


    // 复制宝贝

    public function success($info = '', $url = '')
    {
        echo json_encode(array('info' => $info, 'status' => '1', 'url' => $url));
        exit;
    }


    public function error($info, $url)
    {
        echo json_encode(array('info' => $info, 'status' => '0', 'url' => $url));
        exit;
    }

}

